﻿using FarmSmartSleep.Common.Domain;
using FarmSmartSleep.Common.Domain.BeginTable;
using FarmSmartSleep.Common.Domain.RaiseManagement;
using FarmSmartSleep.Common.Dtos;
using FarmSmartSleep.Common.Infrastructure;
using FarmSmartSleep.Organ.API.Application.SleepInfoCommands.FemaleBeginCommands;
using MediatR;
using System.Net.WebSockets;

namespace FarmSmartSleep.Organ.API.Application.RaiseCommands
{
    public class RaiseCreateHandler : IRequestHandler<RaiseCreateCommand, Result>
    {
        private readonly IBaseRepository<SheepRaiseDeath> sheepRaiseDeathRepository;//死亡管理
        private readonly IBaseRepository<SleepInfor> sleepinforRep;
        private readonly ILogger<ProBeginAllCreateCommand> logger;//日志
        public RaiseCreateHandler(IBaseRepository<SheepRaiseDeath> sheepRaiseDeathRepository, ILogger<ProBeginAllCreateCommand> logger, IBaseRepository<SleepInfor> sleepinforRep)
        {
            this.sheepRaiseDeathRepository = sheepRaiseDeathRepository;
            this.sleepinforRep= sleepinforRep;
            this.logger = logger;
        }

        //private readonly IBaseRepository<SheepDeath> sheepDeathRepository;//死亡原因
        //private readonly IBaseRepository<Cottages> cottagesRepository;//栋舍
        //private readonly IBaseRepository<Fields> fieldsRepository;//栏位
        //private readonly IBaseRepository<SleepInfor> sleepInforRepository;//羊只信息

        /// <summary>
        /// 批量添加羊只死亡
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Result> Handle(RaiseCreateCommand request, CancellationToken cancellationToken)
        {
            try
            {
                var result = new Result() { Code = (int)CodeEnum.success };

                var data = await sheepRaiseDeathRepository.AddRange(request.Datas);
                if (data > 0)
                {
                    // 更新 SleepInfor 表的栋舍栏位
                    request.Datas.ForEach(x =>
                    {
                        var list = sleepinforRep.GetAll().FirstOrDefault(c => c.SleepInforId == x.SleepInforId); 
                        list.StayStatus = 0;
                        sleepinforRep.Update(list);
                    });

                    result.Code = (int)CodeEnum.success;
                    result.Messege = "添加成功";

                }
                return result;
            }
            catch (Exception ex)
            {
                logger.LogError("批量添加羊只死亡信息方法调用失败" + ex);
                throw;
            }
        }
    }
}
